package com.byzk.p2p.admin.fuiou.controller;

import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.borrow.vo.BorrowVo;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.PreAuth;
import com.byzk.p2p.admin.fuiou.util.HttpClientHelper;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.money.dto.WithdrawRecord;
import com.byzk.p2p.admin.money.service.WithdrawService;
import com.byzk.p2p.admin.money.util.WithdrawStatus;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.dto.MemberLevel;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.system.service.MemberService;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserService;

/**
 * app微信托管接口处理
 * @author suker
 *
 */
@Controller
@RequestMapping("/app/fuion")
@Scope("prototype")
public class AppFuionController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private UserAccountService acctountService;
	@Autowired
	private BankCardService bankCardService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private BorrowService borrowService ;
	@Autowired
	private CallbackService callbackService ; 
	@Autowired
	private TenderService tenderservice ;  
	@Autowired
	private FuionAccountController fuionAccountController;
	
	
	/**
	 * app 快捷充值
	 * @param uid     用户id
	 * @param amount  充值金额
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/recharge/quick")
	public String quickPay(@RequestParam("uid")int uid,
						   @RequestParam("amount") String amount) throws Exception{
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String mchnt_cd=Config.mchnt_cd;
		String mchnt_txn_ssn=DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000);
		User user=userService.getById(uid);
		String login_id=user.getPhone();
		String amt=Long.parseLong(amount)*100+"";
		String page_notify_url=Config.server_url+"/app/fuion/angency/recharge";
		String back_notify_url=Config.server_url+"/fuion/recharge/quick/callback";
		String signature=SecurityUtils.sign(amt + "|" + back_notify_url + "|" + login_id+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + page_notify_url);
	    response.setContentType("text/html;charset=UTF-8");
	    
	    String Url = Config.app_recharge_quick_url;
	    try {
	        out.println("<!DOCTYPE html>");
	        out.println("<html>");
	        out.println("<head>");
	        out.println("<title>Servlet RechargeServlet</title>");
	        out.println("</head>");
	        out.println("<body>");
	        out.println("<form action="+Url+" id=\"frm1\" method=\"post\">");
	        out.println("<input type=\"hidden\" name=\"mchnt_cd\" value='" + mchnt_cd + "'>");
	        out.println("<input type=\"hidden\" name=\"mchnt_txn_ssn\" value='" + mchnt_txn_ssn + "'>");
	        out.println("<input type=\"hidden\" name=\"login_id\" value='" + login_id + "'>");
	        out.println("<input type=\"hidden\" name=\"amt\" value='" + amt + "'>");
	        out.println("<input type=\"hidden\" name=\"page_notify_url\" value='" + page_notify_url + "'>");
	        out.println("<input type=\"hidden\" name=\"back_notify_url\" value='" + back_notify_url + "'>");
	        out.println("<input type=\"hidden\" name=\"signature\" value='" + signature + "'>");
	        out.println("</form>");
	        out.println("<script language=\"javascript\">");
	        out.println("document.getElementById(\"frm1\").submit();");
	        out.println("</script>");
	        out.println("</body>");
	        out.println("</html>");
	    } finally {
	        out.close();
	    }	
		return null;
	}
	
	/**
	 * app 快速充值
	 * @param uid      用户id
	 * @param amount   充值金额
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/recharge/speedy")
	public String speedy(@RequestParam("uid")int uid,
						   @RequestParam("amount") String amount) throws Exception{
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String mchnt_cd=Config.mchnt_cd;
		String mchnt_txn_ssn=DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000);
		User user=userService.getById(uid);
		String login_id=user.getPhone();
		String amt=Long.parseLong(amount)*100+"";
		String page_notify_url=Config.server_url+"/app/fuion/angency/recharge";
		String back_notify_url=Config.server_url+"/fuion/recharge/speedy/callback";
		String signature=SecurityUtils.sign(amt + "|" + back_notify_url + "|" + login_id+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + page_notify_url);
	    response.setContentType("text/html;charset=UTF-8");
	    System.out.println("======mchnt_txn_ssn======"+mchnt_txn_ssn);
	    
	    String Url = Config.app_recharge_speedy_url;
	    try {
	        out.println("<!DOCTYPE html>");
	        out.println("<html>");
	        out.println("<head>");
	        out.println("<title>Servlet RechargeServlet</title>");
	        out.println("</head>");
	        out.println("<body>");
	        out.println("<form action="+Url+" id=\"frm1\" method=\"post\">");
	        out.println("<input type=\"hidden\" name=\"mchnt_cd\" value='" + mchnt_cd + "'>");
	        out.println("<input type=\"hidden\" name=\"mchnt_txn_ssn\" value='" + mchnt_txn_ssn + "'>");
	        out.println("<input type=\"hidden\" name=\"login_id\" value='" + login_id + "'>");
	        out.println("<input type=\"hidden\" name=\"amt\" value='" + amt + "'>");
	        out.println("<input type=\"hidden\" name=\"page_notify_url\" value='" + page_notify_url + "'>");
	        out.println("<input type=\"hidden\" name=\"back_notify_url\" value='" + back_notify_url + "'>");
	        out.println("<input type=\"hidden\" name=\"signature\" value='" + signature + "'>");
	        out.println("</form>");
	        out.println("<script language=\"javascript\">");
	        out.println("document.getElementById(\"frm1\").submit();");
	        out.println("</script>");
	        out.println("</body>");
	        out.println("</html>");
	    } finally {
	        out.close();
	    }	
		return null;
	}
	
	/**
	 * @param uid			用户ID
	 * @param amount		提现金额
	 * @param returnUrl		异步回调地址
	 * @param mchnt_txn_ssn	防止并发的code，在检查提现金额时生成
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/withdraw/apply")
	public String withdraw(@RequestParam("uid")int uid,
						   @RequestParam("amount") Double amount, 
						   @RequestParam("returnUrl")String returnUrl,
						   @RequestParam("code")String mchnt_txn_ssn) throws Exception{
		User user=userService.getById(uid);
		UserAccount account=acctountService.getByUserId(user.getId());
		
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String mchnt_cd=Config.mchnt_cd;
		
		String login_id=user.getPhone();
		
		MemberLevel level=memberService.getById(account.getLevel());
		List<WithdrawRecord> recordList=withdrawService.listByDateAndUid(account.getUserId(), DateUtils.formatYearMonth(new Date()));
		Double withdrawFee=0.00;//提现手续费
		if(level.getCount()-recordList.size()<=0){
			withdrawFee=2.00;
		}

		Double d = (amount-withdrawFee)*100;
		String amt=d.intValue()+"";// （提现金额-提现手续费）*100
//		String amt=Long.parseLong(String.valueOf((amount-withdrawFee)*100))+"";// （提现金额-提现手续费）*100、
		String page_notify_url=Config.server_url+"/app/fuion/angency/withdraw";
		String back_notify_url=Config.server_url+"/fuion/withdraw/callback";
		String signature=SecurityUtils.sign(amt + "|" + back_notify_url + "|" + login_id+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + page_notify_url);
	    response.setContentType("text/html;charset=UTF-8");

	    List<BankCard> bankList = bankCardService.listCardByUserId(uid);
	    
	    WithdrawRecord record = new WithdrawRecord();
	    record.setCode(mchnt_txn_ssn);
	    List<WithdrawRecord> listRecord = withdrawService.listByParams(record);
	    if(listRecord != null && listRecord.size() == 0) {//防止并发
	    	WithdrawRecord withdraw = new WithdrawRecord();
	    	withdraw.setCode(mchnt_txn_ssn);
	    	withdraw.setUserId(uid);
	    	withdraw.setCardNo(bankList.get(0).getCardNo());
	    	withdraw.setMoney(amount);
	    	withdraw.setBalance(amount-withdrawFee);
	    	withdraw.setFee(withdrawFee);	
	    	withdraw.setStatus(WithdrawStatus.APPLY);
	    	withdraw.setTerminal("PC");
	    	withdraw.setBankNo(bankList.get(0).getBankName());
	    	withdraw.setCreateTime(new Date());
	    	withdrawService.saveOrUpdate(withdraw);
	    }
		
	    String Url = Config.app_withdraw_url;
	    try {
	        out.println("<!DOCTYPE html>");
	        out.println("<html>");
	        out.println("<head>");
	        out.println("<title>Servlet RechargeServlet</title>");
	        out.println("</head>");
	        out.println("<body>");
	        out.println("<form action="+Url+" id=\"frm1\" method=\"post\">");
	        out.println("<input type=\"hidden\" name=\"mchnt_cd\" value=" + mchnt_cd + ">");
	        out.println("<input type=\"hidden\" name=\"mchnt_txn_ssn\" value=" + mchnt_txn_ssn + ">");
	        out.println("<input type=\"hidden\" name=\"login_id\" value=" + login_id + ">");
	        out.println("<input type=\"hidden\" name=\"amt\" value=" + amt + ">");
	        out.println("<input type=\"hidden\" name=\"page_notify_url\" value=" + page_notify_url + ">");
	        out.println("<input type=\"hidden\" name=\"back_notify_url\" value=" + back_notify_url + ">");
	        out.println("<input type=\"hidden\" name=\"signature\" value=" + signature + ">");
	        out.println("</form>");
	        out.println("<script language=\"javascript\">");
	        out.println("document.getElementById(\"frm1\").submit();");
	        out.println("</script>");
	        out.println("</body>");
	        out.println("</html>");
	    } finally {
	        out.close();
	    }	
		return null;
	}
	
	/**
	 * 预授权(投资)
	 * @return
	 */
	@RequestMapping(value="/transfer/freezen")
	public String transferToFreezen(@RequestParam("borrowId") int borrowId,
									@RequestParam("userId") int userId,
									@RequestParam("amount") String amount){
		BorrowVo vo=borrowService.detailBorrowVo(borrowId);
		User tenderUser=userService.getById(userId);
		User borrowUser=userService.getById(vo.getBorrowUserId());
		
		PreAuth auth=new PreAuth();
		auth.setMchnt_cd(Config.mchnt_cd);
		auth.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
		auth.setOut_cust_no(tenderUser.getPhone());
		auth.setIn_cust_no(borrowUser.getPhone());
		auth.setAmt((int)Double.parseDouble(amount)*100+"");
		auth.setRem("");
		String inputStr=auth.regSignVal();
		auth.setSignature(SecurityUtils.sign(inputStr));
		
		System.out.println("----明文参数："+inputStr);
		
		String backStr="";
		try {
			backStr = WebUtils.sendHttp(Config.pre_auth_url,auth);
			
			System.out.println("-------回调结果:"+backStr);
			
			Callback callback=new Callback("预授权",backStr,new Date());
			callbackService.saveOrUpdate(callback);
			
			String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			String mchnt_txn_ssn=XmlUtils.getXmlNodeValue(backStr, "mchnt_txn_ssn");
			String contract_no=XmlUtils.getXmlNodeValue(backStr, "contract_no");
			if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
				int result=tenderservice.addTender(borrowId,userId,Double.parseDouble(amount),mchnt_txn_ssn,contract_no);
				if(result==1){
					super.printJSON(new JsonMsg(-1, "划拨成功"));
				}else{
					super.printJSON(new JsonMsg(1, "划拨失败","标已投满！"));
				}
			}else{
				super.printJSON(new JsonMsg(1, "划拨失败",resp_code));
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * <p>
	 * Description:富有充值回调中介
	 * </p>
	 * <p>
	 * Company:xbd
	 * </p>
	 * 
	 * @author:lilei
	 * @date:2016年11月25日下午2:51:39
	 */
	@RequestMapping(value = "/angency/recharge")
	public String rechargeAngency() {
		String resp_code = request.getParameter("resp_code");
		String resp_desc = request.getParameter("resp_desc");
		StringBuilder url = new StringBuilder(Config.server_url+"/wx_xbd/recharge_back.html");
		try {
			url.append("?1=1");
			if (null != resp_code && StringUtils.isNotBlank(resp_code)) {
				url.append("&code=" + resp_code);
			}
			if (null != resp_code && StringUtils.isNotBlank(resp_code)) {
				url.append("&msg=" + URLEncoder.encode(resp_desc, "utf-8"));
			}
			response.sendRedirect(url.toString());
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;
	}
	
	
	/**
	 * 
	 * <p>
	 * Description:富有提现回调中介
	 * </p>
	 * <p>
	 * Company:xbd
	 * </p>
	 * 
	 * @author:lilei
	 * @date:2016年11月25日下午2:53:00
	 */
	@RequestMapping(value = "/angency/withdraw")
	public String withDrawAngency() {
		// 获取富有响应参数
		String resp_code = request.getParameter("resp_code");
		String resp_desc = request.getParameter("resp_desc");
		StringBuilder url = new StringBuilder(Config.server_url + "/wx_xbd/withdrawal_back.html");
		try {
			url.append("?1=1");
			if (null != resp_code && StringUtils.isNotBlank(resp_code)) {
				url.append("&code=" + resp_code);
			}
			if (null != resp_code && StringUtils.isNotBlank(resp_code)) {
				url.append("&msg=" + URLEncoder.encode(resp_desc, "utf-8"));
			}
			response.sendRedirect(url.toString());
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;
	}
}
